package com.android.guoqi.sms

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import java.text.SimpleDateFormat
import java.util.*

class SmsReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        if (action == SMS_RECEIVED_ACTION) {
            val bundle = intent.extras
            if (bundle != null) {
                val pdusData = bundle.get("pdus") as Array<Any>
                val msg = arrayOfNulls<SmsMessage>(pdusData.size)
                for (i in msg.indices) {
                    val pdus = pdusData[i] as ByteArray
                    msg[i] = SmsMessage.createFromPdu(pdus)
                }
                val sender = StringBuffer()
                sender.append(msg[0]!!.originatingAddress)
                val content = StringBuffer()
                for (temp in msg)
                    if (temp != null) {
                        content.append(temp.messageBody)
                    }
                val date = msg[0]!!.timestampMillis
                val timeDate = Date(date)
                val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val time = simpleDateFormat.format(timeDate)
                //Log.e("收到短信", "\n短信来自:$sender\n短信内容:$content\n短信时间:$time")
                //Toast.makeText(context, "\n短信来自:$sender\n短信内容:$content\n短信时间:$time", Toast.LENGTH_LONG).show()
                mMessageListener?.OnReceived(sender.toString(), content.toString(), time)

            }
        }
    }

    // 回调接口
    interface MessageListener {
        fun OnReceived(sender: String, content: String, time: String)
    }

    fun setOnReceivedMessageListener(messageListener: MessageListener) {
        mMessageListener = messageListener
    }

    companion object {

        var mMessageListener: MessageListener? = null

        val SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"
    }
}